import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import "taro-ui/dist/style/components/calendar.scss";
import {
  Layout,
  C19CalendarCollapse,
  C36TabBarStandalone,
  C20AllListing,
  WithMargins,
  C39BirthStone,
  ShimmeringText,
  C05CustomerService,
} from "@/components";
import { ItemListingCardShape } from "@/data/shared/entityShapes";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { formatDate } from "@/utils/dateTimeFormatHelpers";
import { useState, useEffect } from "react";
import { useAuth, apiWithAuth } from "@/store/authContext";
import {
  BirthStoneDataType,
  BirthStoneShape,
} from "@/data/birthstones/birthStoneType";
import { ActionKeys, ActionNames, sendAction } from "@/utils/tracking";
import styles from "./index.module.scss";
import "./index.scss";

const CALENDAR_TABS_DATA: {
  tabText: string;
  type: number;
}[] = [
  {
    type: 0,
    tabText: "全部",
  },
  {
    type: 1,
    tabText: "课程",
  },
  {
    type: 2,
    tabText: "讲座",
  },
  {
    type: 3,
    tabText: "展览",
  },
];

// let allData = [];

function CalendarPage() {
  const { dispatchAuthAction } = useAuth();
  const [selectedTabIndex, setSelectedTabIndex] = useState(0);
  const [currentMonth, setCurrentMonth] = useState(1); // arbitrary starting month
  const [currentDate, setCurrentDate] = useState(formatDate(new Date()));
  const [showBirthStone, setShowBirthStone] = useState(false);
  const [currentListData, setCurrentListData] = useState<
    Array<ItemListingCardShape>
  >([]);
  const [expanded, setExpanded] = useState(false);
  const [birthStoneData, setBirthStoneData] = useState(
    {} as BirthStoneDataType
  );
  const [currentGemData, setCurrentGemData] = useState<BirthStoneShape | null>(
    null
  );

  useEffect(() => {
    const date = formatDate(new Date());
    onChangeMonthCallback(date);
    handleDate(date);
    Taro.request({
      url: `${process.env.apiEndpoint}/about/birthstone`,
      success(result) {
        setBirthStoneData(result.data.data.birthstone as BirthStoneDataType);
      },
    });

    sendAction(ActionNames.CalendarImpression);
  }, []);

  useEffect(() => {
    setCurrentGemData(
      birthStoneData[currentMonth.toString()] &&
        birthStoneData[currentMonth.toString()].length > 0
        ? birthStoneData[currentMonth.toString()][0]
        : // ? birthStoneData[currentMonth.toString()].filter(bs => bs.status === true)[0]
          null
    );
  }, [birthStoneData, currentMonth]);

  const handleDateClick = (item: any) => {
    handleDate(item.value);
  };

  //can put toggleCallback and onChangeMonthCallback inside C19 or here.
  const toggleCallback = () => {
    setExpanded(!expanded);
  };

  const onChangeMonthCallback = (currentView) => {
    const month = new Date(currentView).getMonth() + 1;
    setCurrentMonth(month);
  };

  const fetchList = async (dateString: string, listType: number) => {
    await apiWithAuth(
      "/calendar/list",
      (res) => {
        const { data } = res;
        setCurrentListData(data.data.list);
      },
      {
        query: {
          date: dateString,
          limit: process.env.defaultPageSize!,
          page: 1,
          type: listType,
        },
        authDispatch: dispatchAuthAction,
      }
    );
  };

  const handleDate = async (dateString: string) => {
    setCurrentDate(dateString);
    await fetchList(dateString, selectedTabIndex);
  };

  const trackItemClick = (item) => {
    sendAction(ActionNames.CalendarListClick, {
      [ActionKeys.CalendarType]: item.eventType,
      [ActionKeys.CalendarName]: item.name,
      [ActionKeys.CalendarDate]: currentDate,
      [ActionKeys.CalendarTime]: `${item.startTime} - ${item.endTime}`,
    });
  };

  const onBirthStoneTextClick = () => {
    setShowBirthStone(!showBirthStone);
    sendAction(ActionNames.CalendarStoneClick);
  };

  const onTabClick = async (tabIndex: number, tabText: string) => {
    setSelectedTabIndex(tabIndex);
    await fetchList(currentDate, tabIndex);
    sendAction(ActionNames.CalendarColumnClick, {
      [ActionKeys.ColumnName]: tabText,
    });
  };
  const showBirthStonePoster = showBirthStone && currentGemData;

  return (
    <Layout>
      <View className="calendar-wrapper">
        <View>
          <View
            className={`${styles["calendar-area"]} ${
              expanded || showBirthStone ? styles["expanded"] : ""
            }`}
          >
            {currentGemData ? (
              <C19CalendarCollapse
                handleDateClick={handleDateClick}
                toggleCallback={toggleCallback}
                onChangeMonthCallback={onChangeMonthCallback}
                backgroundImage={currentGemData.background!}
              />
            ) : (
              <C19CalendarCollapse
                handleDateClick={handleDateClick}
                toggleCallback={toggleCallback}
                onChangeMonthCallback={onChangeMonthCallback}
              />
            )}
            <View
              className={styles["birth-stone-view"]}
              onClick={onBirthStoneTextClick}
            >
              {currentGemData && (
                <ShimmeringText
                  text={currentGemData.name}
                  textColor="#00a4b6"
                  //textColor={currentGemData.color}
                />
              )}
            </View>
          </View>
          <WithMargins>
            <View className={styles["calendar-listing"]}>
              <C36TabBarStandalone
                tabs={CALENDAR_TABS_DATA.map(
                  (calendarTab) => calendarTab.tabText
                )}
                onTabClickCb={(clickedTabIndex) =>
                  onTabClick(
                    clickedTabIndex,
                    CALENDAR_TABS_DATA[clickedTabIndex].tabText
                  )
                }
                type="discover"
                activeTabIdx={selectedTabIndex}
              />

              <C20AllListing
                cardList={currentListData.map((eventData: any) => ({
                  ...eventData,
                  eventType: apiItemTypeMapping[eventData.type],
                  upperRightText: eventData.isAppointment ? "已预约" : null,
                  link: `pages/${
                    apiItemTypeMapping[eventData.type]
                  }-detail/index?id=${eventData.id}`,
                }))}
                cardType="vertical-list-card-spread"
                onItemClick={trackItemClick}
              />
            </View>
          </WithMargins>
        </View>
      </View>
      <C05CustomerService />
      {/* Birth stone overlay */}
      {showBirthStonePoster && (
        <View
          className={styles["birthstone-info-placement"]}
          style={{ position: "absolute", top: 0 }}
        >
          <C39BirthStone
            poster={currentGemData.image!}
            link={currentGemData.link!}
            name={currentGemData.name!}
            closeCb={(evt) => {
              evt?.stopPropagation();
              setShowBirthStone(false);
            }}
          />
        </View>
      )}
    </Layout>
  );
}

export default CalendarPage;
